#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# Edit By WangWenHao, CMIOT, China Mobile

import sys
import time
import pandas as pd
import numpy as np

def time2min(t):
	h,m = t.strip().split(":")
	return int(h) * 60 + int(m)

def min2time(min_cnt):
	h, m = divmod(min_cnt, 60)
	str = "%d:%d" % (h,m)
	return str


def main():
	# read the sleepdata as df
	df = pd.read_csv('../sleepdata.csv', sep = ";")

	# Delete 'wake up','Sleep Notes', 'Activity' cols
	df.drop(['Wake up'],axis=1,inplace=True)
	df.drop(['Sleep Notes'],axis=1,inplace=True)
	df.drop(['Activity (steps)'],axis=1,inplace=True)

	################# creat new data ##################
	NeedDel = []
	j=0
	for i in range(1, len(df)):
		timeArray = time.strptime(df['Start'][i], "%Y-%m-%d %H:%M:%S")  #format time
		timeStart = int(time.mktime(timeArray))                         #value time
		timeTemp = time.strptime(df['End'][i-1], "%Y-%m-%d %H:%M:%S")
		timeEnd = int(time.mktime(timeTemp))
		bedTime_1 = time2min(df['Time in bed'][i-1])                    #string time to miniutes
		bedTime_2 = time2min(df['Time in bed'][i])
		slpQuilty_1 = int(df['Sleep quality'][i-1].strip("%"))          #value %
		slpQuilty_2 = int(df['Sleep quality'][i].strip("%"))

		#if bedtime is too small, maybe device error occasionally
		if (timeStart - timeEnd) < 3600:
			df['Time in bed'][i-1] = min2time(bedTime_1 + bedTime_2)
			df['End'][i-1] = df['End'][i]
			#print("Delete later: %s", df.loc[i])
			if slpQuilty_1 < slpQuilty_2:
				df['Sleep quality'][i-1] = df['Sleep quality'][i]
			else:
				pass
			NeedDel.append(1)
			NeedDel[j] = i
			j = j+1
			#print("Already modified: %s", df.loc[i-1])
		else:
			pass

	#del useless line		
	df.drop(NeedDel, inplace = True)
	df.index = range(0, len(df))
	#print(df)
	newindex = []
	#add 24 hours to midnight
	for i in range(0, len(df)):
		timeArray = time.strptime(df['Start'][i], "%Y-%m-%d %H:%M:%S")  #format time
		newindex.append("%02d-%02d-%02d" % (timeArray.tm_year, timeArray.tm_mon, timeArray.tm_mday))
		if(timeArray.tm_hour < 6):
			df['Start'][i] = "%02d-%02d-%02d %02d:%02d:%02d" % (timeArray.tm_year, timeArray.tm_mon,\
				timeArray.tm_mday, timeArray.tm_hour+24, timeArray.tm_min, timeArray.tm_sec)

	################# creat new data ##################
	print(newindex)
	print(len(newindex))
	print(len(df))
	df['newindex'] = newindex
	df.set_index('newindex', inplace = True)
	#print(df)
	df.to_csv('../newdata_0.csv', sep = ";", index =True)



if __name__ == '__main__':
	print("Dodata start...")
	main()
    # print(__name__)